package web.dao.impls;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import map.beans.MapToolConfigBean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import web.dao.interfaces.MapToolConfigDao;

@Repository("mapToolsDao")
@Transactional(readOnly = true)
public class MapToolConfigDaoImpl implements MapToolConfigDao {
	private static Logger LOGGER = LoggerFactory.getLogger(MapToolConfigDaoImpl.class);
	
	@PersistenceContext
	private EntityManager entityManager;
	

	@Override
	@Transactional
	public List<MapToolConfigBean> findAll() {
		TypedQuery<MapToolConfigBean> query = entityManager.createQuery("SELECT t FROM MapToolConfigBean t ORDER BY t.id", MapToolConfigBean.class);
		return query.getResultList();
	}

	@Override
	public Long save(MapToolConfigBean mapTool) {try {
		System.out.println("........... Persisting Object  " + mapTool.getName() + "  .............."); 

		entityManager.persist(mapTool);
		entityManager.flush();
	} catch (Exception e) {
		LOGGER.error(e.getMessage());	
	}
	return mapTool.getId();
	}

	@Override
	public Long update(MapToolConfigBean mapTool) {
		try {
			System.out.println("........... Updating Object " + mapTool.getName() + "  .............."); 
			entityManager.merge(mapTool);
			entityManager.flush();
		} catch (Exception e) {
			e.printStackTrace();		
		}
		return mapTool.getId();
	}

	@Override
	public boolean delete(MapToolConfigBean mapTool) {
		// check that it exists in the DB
		mapTool = entityManager.getReference(MapToolConfigBean.class, mapTool.getId());
		boolean status = false;
		
		if (mapTool != null) {					
			entityManager.remove(mapTool);
			entityManager.flush();
			status = true;
		}
		return status;
	}

	@Override
	public MapToolConfigBean getMapTool(Long id) {
		MapToolConfigBean mapTool = entityManager.find(MapToolConfigBean.class, id);
		
		return mapTool;
	}

}
